const nodeCmd = require('node-cmd')
var log4js = require('./config/logger');
var logger = log4js.getLogger('status');

const watc_pros = [
    `AutoWriteRobotManageServer_yinhe_55585`,
    `pm2-logrotate`
];//监控程序pm2 App Name

function do_cmd(cmd,callback) {
    return new Promise((resolve, reject) => {
        nodeCmd.get(cmd, function (err, data, stderr) {
            if (err) {
                logger.error(`cmd ${cmd} error ${JSON.stringify(err)}`)
                reject(err);
            }
            logger.info(`command ${cmd} success ` + data.toString());
            callback && callback(data)
            resolve(data);
        })
    })
}

    
/**机器内存监听 */
async function watch_memery() {
    let shellMsg = await do_cmd("free -m | awk '{print $4}'").catch(e => {
        return null
    });
    logger.info(`机器内存监听: ${shellMsg}`);
    if (shellMsg) {
        let freeMem = shellMsg.split('\n')[1];
        logger.info(`free memery is ${freeMem}M`);
        let isRestartDay = false;//默认都不是重启日期
        let isRestartTime = false;//默认都不是重启时间
        let date = new Date();
        let day = date.getDate();
        logger.info(`当前day:${day},typeof:${typeof day}`)
        let hours = date.getHours();
        let minutes = date.getMinutes();
        logger.info(`当前hours:${hours},minutes:${minutes}`)
        if((hours > 9 && hours < 12) || (hours > 13 && hours < 16)){
            isRestartTime =  false;
            logger.info("机器写稿定时任务执行时间，不能重启进程")
        } else {
            isRestartTime =  true;
            logger.info("机器写稿定时任务执行时间，可以重启进程")
        };
        if(day == 5 || day == 15 || day == 25){
            isRestartDay = true;//每个月的5号、15号、25号重启进程，因为定时器15天左右就失效，存在问题，所以10天左右重启
            logger.info("10天时间到，可以重启进程")
        }
        if ((parseInt(freeMem) < 3000 || isRestartDay ) && isRestartTime) {
            logger.warn("memery too litter,free memery is:" + freeMem)
            for (let appName of watc_pros) {
                logger.info(`start stop ${appName}`)
                await do_cmd(`pm2 stop ${appName}`)
                logger.info(`stop ${appName} process success!restart it after 60s`)
                await do_cmd(`echo 1 > /proc/sys/vm/drop_caches`)
                await do_cmd(`echo 2 > /proc/sys/vm/drop_caches`)
                await do_cmd(`echo 3 > /proc/sys/vm/drop_caches`)
                setTimeout(() => {
                    do_cmd(`pm2 restart ${appName}`)
                },1000 * 60);
            }
        } else {
            logger.info("memery free")
        }
    }
}
// 程序监听
async function _watcher() {
    for (let appName of watc_pros) {
        let app_detail = await do_cmd(`pm2 show ${appName}`).catch( e => {
            logger.error(`show ${appName} failed!`)
            return null;
        });
        if(app_detail){
            const sta_reg = /(online|stopped)/g;
            let match_obj = sta_reg.exec(app_detail.toString());
            let app_state = match_obj ? match_obj[0] : null;
            if (app_state === "online") {
                // logger.info(`the ${appName} is online`)
            } else if (app_state === "stopped") {
                logger.warn(`the ${appName} is stopped,please restart`);
                do_cmd(`pm2 restart ${appName}`)
            } else {
                logger.error(`the app_state is ${app_state}`)
            }
        }
    }
}

_watcher();
watch_memery();

// 一分钟检查一次内存
setInterval(() => {
    watch_memery()
},1000 * 60 * 1);

// 十分钟检测一次程序状况
setInterval(() => {
    _watcher()
}, 1000 * 60 * 10)

